#pragma once
#include <stdio.h>
#include "table.h"
#include "cstring.h"

// 默认的分隔符是等号
// #define SC_SEP_CHAR '='

#define SC_SEP_CHAR ' '

string sc_encode(table); // 将哈希表编码为sc字符串
int sc_decode(string, table); // 将sc字符串解析到哈希表

/* size_t sc_eval(const char*); // 评估一个sc文件并给出关于缓冲区大小的建议
int sc_save(table, const char*); // 储存sc文件
int sc_load(const char*, table, char*, size_t); // 导入sc文件
int sc_patch(const char*, const char*, const char*); // 在文件中增量写入一条新配置 */



// ------- 具体实现 ------- //

string sc_encode(table tb) {
	string sc = String.new("");
	for (kvp* in_pairs(tb, itm)) {
		sc = String.concat(sc, String.format("%s%c%s\n", itm->key, SC_SEP_CHAR, itm->val));
	}
	return sc;
}

int sc_decode(string sc, table tb) {
	int count = 0;
	while (sc->length > 0) {
		size_t endOfLine = String.findchar(sc, '\n'); // 找到一行的结尾
		if (!endOfLine) break;
		string line = String.sub(sc, 0, endOfLine); // 截取这一行
		sc = String.sub(sc, endOfLine + 1, sc->length); // 剩余的字符串
		
		size_t sepPos = String.findchar(line, SC_SEP_CHAR); // 找到分隔符的位置
		if (!sepPos) return -1;
		string key = String.sub(line, 0, sepPos); // 取出键
		string val = String.sub(line, sepPos + 1, line->length); // 取出值
		tb_set(tb, key->cstr, val->cstr);
		count++;
	}
	return count;
}

/*
size_t sc_eval(const char* filepath) {
	FILE *file = fopen(filepath, "rb");
	if (!file) return 0;
	
	fseek(file, 0, SEEK_END);
	size_t size = (size_t)ftell(file) + 1;
	fclose(file);

	return size;
}

int sc_save(table tb, const char* filepath) {
	FILE *file = fopen(filepath, "wb");
	if (!file) return 0;
	
	for (kvp* in_pairs(tb, itm))
		fprintf(file, "%s%c%s\n", itm->key, SC_SEP_CHAR, itm->val);

	return 1;
}

int sc_load(const char* filepath, table tb, char* buffer, size_t size) {
	FILE *file = fopen(filepath, "rb");
	if (!file) return 0;
	
	fread(buffer, 1, size, file);
	fclose(file);
	buffer[size-1] = '\0';
	
	return sc_decode(buffer, tb);
}

int sc_patch(const char* filepath, const char* key, const char* val) {
	FILE *file = fopen(filepath, "ab");
	if (!file) return 0;
	
	fprintf(file, "%s%c%s\n", key, SC_SEP_CHAR, val);
	return 1;
} */